﻿using System;
using System.Reflection;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    // 无参构造
    public Person() => Console.WriteLine("无参构造被调用");

    // 公有带参构造
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
        Console.WriteLine($"公有构造：{Name} {Age}");
    }

    // 私有构造
    private Person(int age)
    {
        Age = age;
        Console.WriteLine($"私有构造：{Age}");
    }
}

class Program
{
    static void Main()
    {
        // 调用无参构造
        Type type = typeof(Person);
        ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
        Person p1 = (Person)defaultCtor.Invoke(null);
        Console.WriteLine($"创建对象：{p1.GetType().Name}\n");

        // 调用公有带参构造
        ConstructorInfo paramCtor = type.GetConstructor(new[] { typeof(string), typeof(int) });
        Person p2 = (Person)paramCtor.Invoke(new object[] { "张三", 25 });
        Console.WriteLine($"年龄：{p2.Age}\n");

        // 调用私有构造
        ConstructorInfo privateCtor = type.GetConstructor(
            BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            new[] { typeof(int) },
            null);
        Person p3 = (Person)privateCtor.Invoke(new object[] { 30 });
        Console.WriteLine($"私有构造年龄：{p3.Age}\n");

        // 异常处理示例
        try
        {
            ConstructorInfo invalidCtor = type.GetConstructor(new[] { typeof(bool) });
            invalidCtor.Invoke(new object[] { true });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误：{ex.GetBaseException().Message}");
        }
    }
}